const { $util } = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lat: '',
    lng: '',
    markers: [],
    isshowinfo: false,
    scale: 16,
    defaultLat: -1,
    defaultLng: -1,
    imgUrl: $util.getImgUrl(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(opts) {
    this.loadInfo();
    wx.setNavigationBarTitle({
      title: opts.barTitle && decodeURIComponent(opts.barTitle) || '党建地图',
    });
  },
  onReady() {
    this.mapCtx = wx.createMapContext('map1');
  },
  onShow() {
    this.setData({
      scale: 16,
    });
  },
  loadInfo() {
    $util.request({
      url: 'entry/wxapp/partyman.home.getorganlist',
      data: {},
      success: (res) => {
        let idx = res.data.findIndex((item)=>  Number(item.pid) === 0);
        this.setData({
          markers: res.data,
          defaultLat: res.data[idx].latitude ? res.data[idx].latitude : -1,
          defaultLng: res.data[idx].latitude ? res.data[idx].longitude : -1,
        });
        this.initScope();
      },
    });
  },
  /**
   * 获取打开位置权限
   */
  initScope() {
    wx.getSetting({
      success: (res) => {
        console.log(res);
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: (e) => {
              console.log(e);
              this.getLocation();
            },
          });
        } else {
          this.getLocation();
        }
      },
    });
  },
  getLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          lat: res.latitude,
          lng: res.longitude,
        });
      },
    });
  },
  showmarkerinfo(e) {
    const { markerId } = e;
    const { markers } = this.data;
    let markerIdx = 0;
    for (const i in markers) {
      if (markers[i].id === markerId) {
        markerIdx = i;
      }
    }
    this.setData({
      isshowinfo: true,
      markerIdx,
    });
  },
  gosearch() {
    wx.navigateTo({
      url: '/ws_party_const/pages/map/search',
    });
  },
  showpoints() {
    this.initScope();
    this.mapCtx.translateMarker({
      markerId: 0,
      autoRotate: true,
      duration: 1000,
      destination: {
        latitude: this.data.lat,
        longitude: this.data.lng,
      },
    });
  },
  openlocation() {
    const { markerIdx, markers } = this.data;
    wx.openLocation({
      latitude: Number(markers[markerIdx].latitude),
      longitude: Number(markers[markerIdx].longitude),
      name: markers[markerIdx].name,
      address: markers[markerIdx].address,
      scale: 18,
    });
  },
});
